<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span
          class="arrow"
          @click="$router.back()"
        ><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id?'编辑企业':'添加企业' }}</span>
      </div>
      <div class="right">黑马程序员</div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form
            ref="ruleForm"
            label-width="100px"
            :model="addForm"
            :rules="addRules"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <!-- 上传按钮：
                el-upload包裹(里面放置展示的结构)
                action表示上传文件的地址(一般不会直接上传，上传=校验+上传)，#表示不传递
                before-upload表示上传前的方法
                http-request表示上传的方法
                file-list表示上传文件的列表
                limit设置最大上传文件数量
                on-exceed超出文件数量的回调函数
                on-remove=移除文件的钩子函数
               -->
              <el-upload
                action="#"
                :before-upload="beforeUpload"
                :http-request="uploadRequest"
                :file-list="fileList"
                :limit="1"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过 5MB
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="createEnterprise">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getIndustryListAPI, uploadAPI, createEnterpriseAPI, getEnterpriseDetailAPI, editEnterpriseAPI } from '@/api/enterprise'
export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      // 行业列表
      industryList: [],
      //   营业执照上传的列表
      fileList: [],
      //   表单校验规则
      addRules: {
        name: [
          { required: true, message: '企业名称为必填', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '法人为必填', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '注册地址为必填', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '所在行业为必填', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '企业联系人为必填', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '企业联系人电话为必填', trigger: 'blur' }
        ],
        businessLicenseId: [
          { required: true, message: '请上传营业执照', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  created() {
    // 获取行业列表
    this.getIndustryList()
    if (this.id) {
      // 获取企业详情
      this.getEnterpriseDetail()
    }
  },
  methods: {
    async getIndustryList() {
      const { data } = await getIndustryListAPI()
      this.industryList = data
    },
    beforeUpload(file) {
      if (this.fileList.length > 0) {
        this.$message.error('只能上传一张营业执照')
        return false
      }
      console.log('上传前', file)
      const accessTypeList = ['image/png', 'image/jpg', 'image/jpeg']
      const maxSize = 2 * 1024 * 1024
      //   类型校验是否通过
      const typeFlag = accessTypeList.includes(file.type)
      if (!typeFlag) {
        this.$message.error('只能上传jpg/png文件')
      }
      //   文件大小校验是否通过
      const sizeFlag = file.size <= maxSize
      if (!sizeFlag) {
        this.$message.error('文件大小不能超过 5MB')
      }
      return typeFlag && sizeFlag
    },
    // 上传文件的方法(file表示要上传的文件)
    async uploadRequest(data) {
      console.log(this.fileList)

      console.log('上传文件', data.file)
      //   后台上传文件要求的格式-multipart/form-data
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('type', 'businessLicense')
      //   formData就是要传给后台的数据
      const res = await uploadAPI(formData)
      console.log(res)
      this.addForm.businessLicenseId = res.data.id
      this.addForm.businessLicenseUrl = res.data.url
      // 上传成功后，把上传的文件信息添加到fileList中
      this.fileList.push({
        name: data.file.name,
        url: res.data.url
      })
      //   自动校验没有更新，上传完之后，手动再校验一次，更新校验结果
      this.$refs.ruleForm.validate((valid) => {
        console.log(valid)
      })
    },
    // 新增企业方法
    createEnterprise() {
      // 进行表单的统一校验
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.id) {
            // 编辑企业
            const data = { ...this.addForm }
            // 删除对象多余的属性
            delete data.businessLicenseName
            delete data.industryName
            delete data.rent
            const res = await editEnterpriseAPI(data)
            if (res.code === 10000) {
              this.$message.success('更新成功')
              this.$router.back()
            } else {
              this.$message.error('更新失败,' + res.msg)
            }
          } else {
            const res = await createEnterpriseAPI(this.addForm)
            console.log(res)
            if (res.code === 10000) {
              this.$message.success('新增成功')
              this.$router.back()
            } else {
              this.$message.error('新增失败,' + res.msg)
            }
          }
        }
      })
    },
    // 超出上传文件数量限制时的钩子函数
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    handleRemove(file, fileList) {
      // 移除文件时，把fileList中对应的文件信息删除
      this.fileList = fileList
      // 重置表单
      this.addForm.businessLicenseId = ''
      this.addForm.businessLicenseUrl = ''
    },
    // 获取企业详情
    async getEnterpriseDetail() {
      const { data } = await getEnterpriseDetailAPI(this.id)
      console.log(data)
      //     把企业详情赋值给表单
      this.addForm = data
      //     把营业执照信息赋值给fileList
      this.fileList = [{
        name: data.businessLicenseName,
        url: data.businessLicenseUrl
      }]
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
